<template>
  <div class="user-page">
    <div class="search-field">
      <el-form :model="searchForm" inline>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="searchForm.username" autocomplete="off" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="角色名" prop="roleId">
          <el-select v-model="searchForm.roleId" placeholder="选择角色">
            <el-option
              v-for="option in roleList"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>
            <el-button type="primary" @click="startSearch"> 查询 </el-button>
            <el-button  @click="startClear"> 清空 </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="user-page-content">
      <div class="btns-fun-field">
        <el-button
          type="primary"
          @click.prevent="showAddEditDialog"
          :icon="Plus"
        >
          新增用户
        </el-button>
      </div>
      <div class="table-field">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="tableLoading"
        >
          <el-table-column prop="id" label="id" width="190" />
          <!-- <el-table-column label="头像" width="80">
          <template #default="scope">
            <el-image
              :preview-teleported="true"
              style="width: 40px; height: 40px"
              :src="scope.row.avatar"
              :preview-src-list="[scope.row.avatar]"
            >
              <template #error>
                <div class="image-slot">
                  <el-icon><icon-picture /></el-icon>
                </div>
              </template>
            </el-image>
          </template> -->
          <!-- </el-table-column> -->
          <el-table-column prop="username" label="用户名" width="150" >
            <template #default="scope">
              <div v-if="!scope.row.username || scope.row.username=='NULL'"></div>
              <div v-else>{{ scope.row.username }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="nickname" label="昵称" width="180" />
          <el-table-column prop="roleName" label="角色名" width="160">
            <!-- <template #default="scope">
              <div class="tag-field">
                <el-tag v-for="item in scope.row.roleNme" :key="item.id">{{
                  item.roleName
                }}</el-tag>
              </div>
            </template> -->
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="170" />
          <el-table-column label="操作" fixed="right" min-width="220px">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click.prevent="showUpdatePassword(scope.row)"
                >重置密码</el-button
              >
              <el-button
                type="success"
                size="small"
                @click.prevent="showAddEditDialog(scope.row, 2)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="small"
                @click.prevent="showRemoveDialog(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-field">
        <el-pagination
          v-model:current-page="formData.pageIndex"
          v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <el-dialog
      v-if="addDialogVisible"
      v-model="addDialogVisible"
      :title="addEditForm.title"
      width="550px"
    >
      <div style="padding-right: 50px">
        <el-form
          :model="addEditForm"
          :rules="addEditRules"
          ref="addEditRef"
          :label-width="80"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              placeholder="请输入用户名"
              v-model="addEditForm.username"
              autocomplete="off"
              :disabled="addEditForm.disabled || addEditForm.id"
            />
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="!addEditForm.id">
            <el-input
              placeholder="请输入密码"
              v-model="addEditForm.password"
              autocomplete="off"
              :disabled="addEditForm.disabled"
            />
          </el-form-item>
          <el-form-item label="角色" prop="roleId">
            <el-select
              v-model="addEditForm.roleId"
              placeholder="请选择角色"
              style="width: 100%"
              :disabled="addEditForm.disabled"
            >
              <el-option
                v-for="option in roleList"
                :key="option.id"
                :label="option.name"
                :value="option.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input
              placeholder="请输入昵称"
              v-model="addEditForm.nickname"
              autocomplete="off"
              :disabled="addEditForm.disabled"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer v-if="!addEditForm.disabled">
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="requestAddUser"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>


    <el-dialog
      v-if="updatePasswordDialogVisible"
      v-model="updatePasswordDialogVisible"
      :title="updatePasswordEditForm.title"
      width="550px"
    >
      <div style="padding-right: 50px">
        <el-form
          :model="updatePasswordEditForm"
          :rules="updatePasswordEditRules"
          ref="updatePasswordRef"
          :label-width="80"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              readonly
              placeholder="请输入用户名"
              v-model="updatePasswordEditForm.username"
              autocomplete="off"
            />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              placeholder="请输入密码"
              v-model="updatePasswordEditForm.password"
              autocomplete="off"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer v-if="!addEditForm.disabled">
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="requestUpdatePassword"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog
      v-if="removeDialogVisible"
      v-model="removeDialogVisible"
      title="删除用户"
      width="400px"
    >
      <span>确定要删除当前用户？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="removeDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="startRemoveRole"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import {
  getUserPagination,
  getRoleAllList,
  removeUser,
  updateUser,
  updateUserPassword,
  addUser
} from "@/api/user-manage.api";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import type { FormInstance } from "element-plus";

const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});

const searchForm = reactive({
  username: "",
  roleId: "",
});

const removeDialogVisible = ref(false);
const addDialogVisible = ref(false);
const addEditRef = ref<FormInstance>();
const addEditForm = reactive({
  id: null,
  password: "123456",
  nickname: "",
  phonenumber: "",
  username: "",
  disabled: false,
  title: "",
  roleId: "",
});
const addEditRules = reactive({
  username: [
    { required: true, message: "请输入11位手机号作为用户名", trigger: "blur" },
    {
      min: 11,
      max: 11,
      message: "请输入11位手机号作为用户名",
      trigger: "blur",
    },
  ],
  roleId: [{ required: true, message: "请选择用户角色", trigger: "blur" }],
  password: [
    { required: true, message: "请输入6~30位密码", trigger: "blur" },
    { min: 6, max: 30, message: "请输入6~30位密码", trigger: "blur" },
  ],

});

/***
 * 开始搜索
 */
const startSearch = () => {
  let formData= { 
    roleId: undefined,
    username: ''
  };
  if (searchForm.roleId) {
    formData.roleId = searchForm.roleId;
  }
  if (searchForm.username) {
    formData.username = searchForm.username;
  }
  getDataList(formData);
};

/***
 * 清空搜索条件
 */
const startClear = () => {
  searchForm.roleId = "";
  searchForm.username = "";
  getDataList();
};

const showAddEditDialog = (item: any, type: number) => {
  //新增用户
  if (item.target) {
    addEditForm.id = null;
    addEditForm.username = "";
    addEditForm.password = "123456";
    addEditForm.nickname = "";
    addEditForm.phonenumber = "";
    addEditForm.roleId = "";
    addEditForm.disabled = false;
    addEditForm.title = "新增用户";
    addDialogVisible.value = true;
    return;
  }

  addEditForm.id = item.id;
  addEditForm.username = item.username;
  addEditForm.password = item.password;
  addEditForm.nickname = item.nickname;
  addEditForm.phonenumber = item.phonenumber;
  addEditForm.roleId = item.roleId;
  //查看详情
  if (type === 1) {
    addEditForm.title = "查看详情";
    addEditForm.disabled = true;
    addDialogVisible.value = true;
    return;
  }

  //编辑
  addEditForm.title = "编辑用户";
  addEditForm.disabled = false;
  addDialogVisible.value = true;
};


const updatePasswordDialogVisible = ref(false);
const updatePasswordEditForm = reactive({
  username: '',
  password: '',
  userId: '',
  title: "重置密码"
});
const updatePasswordRef = ref<FormInstance>();
const updatePasswordEditRules = 
  {
    username: [
      { required: true, message: "请输入11位手机号作为用户名", trigger: "blur" },
      {
        min: 11,
        max: 11,
        message: "请输入11位手机号作为用户名",
        trigger: "blur",
      },
    ],
    password: [
      { required: true, message: "请输入6~30位密码", trigger: "blur" },
      { min: 6, max: 30, message: "请输入6~30位密码", trigger: "blur" },
    ],
  }


const tableLoading = ref(false);
const tableData = ref([]);

const curSelectRow = ref({
  id: ''
});
const showRemoveDialog = (item: any) => {
  removeDialogVisible.value = true;
  curSelectRow.value = item;
  console.log("item: ", item);
};

const startRemoveRole = () => {
  console.log("...")
  let id = curSelectRow.value.id;
  removeUser([id])
    .then((res) => {
      console.log("success~~~~~", res);
      removeDialogVisible.value = false;
      ElMessage({
        message: "用户删除成功",
        type: "success",
      });
      getDataList();
    })
    .catch((err) => {
      ElMessage({
         message: err.msg || err,
        type: "error",
      });
    });
};

const showUpdatePassword = ( item:any )=>{
  console.log("...", item);
  updatePasswordDialogVisible.value = true;
  updatePasswordEditForm.password = "";
  updatePasswordEditForm.username = item.username;
  updatePasswordEditForm.userId = item.id + "";
}
const requestUpdatePassword = ()=>{
  let formData = {
     userId: updatePasswordEditForm.userId,
     password: updatePasswordEditForm.password
  }
  if (!updatePasswordRef.value) return;
  updatePasswordRef.value.validate(( valid ) => {
    if (valid) {
      updateUserPassword(formData).then(()=>{
          updatePasswordDialogVisible.value = false;
          ElMessage({
              message: "密码重置成功",
              type: "success",
            });
      } ).catch( err=>{
          ElMessage({
              message: err.msg || err,
              type: "error",
            });
      } )
    }
  });

}

const requestAddUser = () => {
  console.log("...")
  let formData = {
    username: addEditForm.username,
    password: addEditForm.password,
    nickname: addEditForm.nickname,
    roleId: addEditForm.roleId,
  };

  if (!addEditRef.value) return;
  addEditRef.value.validate(( valid ) => {
    if (valid) {
      if (addEditForm.id) {
        updateUser({
          ...formData,
          id: addEditForm.id,
        })
          .then((res) => {
            console.log(res)
            addDialogVisible.value = false;
            ElMessage({
              message: "用户修改成功",
              type: "success",
            });
            getDataList();
          })
          .catch((err) => {
            ElMessage({
               message: err.msg || err,
              type: "error",
            });
          });
        return;
      }

      addUser(formData)
        .then((res) => {
          console.log(res)
          addDialogVisible.value = false;
          ElMessage({
            message: "用户新增成功",
            type: "success",
          });
          getDataList();
        })
        .catch((err) => {
          ElMessage({
             message: err.msg || err,
            type: "error",
          });
        });
    }
  });
};

const handleSizeChange = (value: number) => {
  console.log("handleSizeChange...", value);
  formData.pageSize = value;
  getDataList();
};

const handleCurrentChange = (value: number) => {
  console.log("handleCurrentChange...", value);
  formData.pageIndex = value;
  getDataList();
};

const getDataList = (searchCondition = {}) => {
  tableLoading.value = true;
  getUserPagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
    ...searchCondition,
  })
    .then(function (res: any) {

      let list =res.list || [];
      list = list.map( item=>{
        let roleId = item.roleId;
        console.log(roleId ,roleList.value)
        let roleItem = roleId && roleList.value.find( row=>{
          return row.id == roleId;
        });
        console.log("roleItem: ", roleItem)
        if( roleItem ){
          item.roleName = roleItem.name;
        }
        return item;
      })
      tableData.value = list;
      formData.total = Number(res.total);
      tableLoading.value = false;


      roleList
    })
    .catch((error) => {
      console.log(error);
      tableLoading.value = false;
    });
};

const roleList = ref([]);
const startGetAllRoleList = async () => {
  try {
    console.log("...")
    let res:any = await getRoleAllList();
    console.log("startGetAllRoleList: ", res);
    roleList.value = res;
  } catch( err ){
    console.log("startGetAllRoleList: ",err)
  }
};

onMounted( async () => {
  await startGetAllRoleList();
  getDataList();
});
</script>
<style lang="scss" scoped>
@import "./UserList.scss"
</style>
